package rabbit.common;

import com.sun.org.apache.xml.internal.serialize.XMLSerializer;

import javax.xml.bind.JAXB;
import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.OutputStream;

/**
 * Created by root on 17-4-15.
 */
public class XmlSerializerHelper {



    public static String serialize(Class type, Object toSerialize, String encoding){

        XMLEncoder encoder=null;
        try{
            String output = "";
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            JAXB.marshal(toSerialize,os);
            output = new String(os.toByteArray());

            return output;
        }
        catch (Exception ex){
            System.out.println(ex.getMessage());
            return "";
        }
        finally {
            if(encoder!=null){
                encoder.close();
            }
        }
    }

    public static <T> T deserialize(Class type, String path) throws ArrayIndexOutOfBoundsException {
        XMLDecoder decoder =null;

        try{
            FileInputStream inputStream = new FileInputStream(path);
            T result = (T)JAXB.unmarshal(inputStream,type);
            return result;
        }catch (Exception ex){
            if(ex instanceof ArrayIndexOutOfBoundsException){
                throw (ArrayIndexOutOfBoundsException)ex;
            }
            System.out.println(ex.getMessage());
            return null;
        }finally {
            if(decoder!=null){
                decoder.close();
            }
        }
    }
}
